//
//  STViewController.m
//  SwipeTableView
//
//  Created by Roy lee on 16/4/1.
//  Copyright © 2016年 Roy lee. All rights reserved.
//

#import "STViewController.h"
#import "SwipeTableView.h"
#import "CustomTableView.h"
#import "UIView+STFrame.h"
#import "STImageController.h"
#import "STTransitions.h"
#import "STRefresh.h"
#import <objc/message.h>
#import "MJRefresh.h"
#import "aRModel.h"
#import "MBProgressHUD.h"
#import "aRquestModel.h"
#import "PlayViewController.h"
#import "MusicTool.h"
#import "HMSegmentedControl.h"
#import <ReactiveCocoa/ReactiveCocoa.h>
#import "STViewModel.h"

@interface STViewController ()<SwipeTableViewDataSource,SwipeTableViewDelegate,UIGestureRecognizerDelegate,UIViewControllerTransitioningDelegate>

@property (nonatomic, strong) SwipeTableView       * swipeTableView;
@property (nonatomic, strong) STHeaderView         * tableViewHeader;
@property (nonatomic, strong) HMSegmentedControl   * hsBar;
@property (nonatomic, strong) CustomTableView      * tableView;
@property (nonatomic, strong) NSMutableDictionary  * dataDic;
@property (nonatomic, strong) UIImageView          * gifView;
@property (nonatomic, assign) NSInteger              index;
@property (nonatomic, strong) UITapGestureRecognizer *tap;
@property (nonatomic, strong) UIButton             *rightBtn;
@property (nonatomic, strong) UIBarButtonItem      * leftBarItem;
@property (nonatomic, strong) STViewModel          * stModel;

@end

@implementation STViewController

- (CustomTableView *)tableView {
    if (nil == _tableView) {
        _tableView = [[CustomTableView alloc]initWithFrame:_swipeTableView.bounds style:UITableViewStylePlain];
        _tableView.backgroundColor = aR_BGColor;
    }
    return _tableView;
}

-(SwipeTableView *)swipeTableView {
    if (nil == _swipeTableView) {
        _swipeTableView = [[SwipeTableView alloc]initWithFrame:self.view.bounds];
        _swipeTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
        _swipeTableView.delegate   = self;
        _swipeTableView.dataSource = self;
        _swipeTableView.shouldAdjustContentSize = YES;
        _swipeTableView.swipeHeaderView = _type?nil:self.tableViewHeader;
        _swipeTableView.swipeHeaderBar = self.hsBar;
        _swipeTableView.swipeHeaderBarScrollDisabled = STControllerTypeDisableBarScroll;
        if (STControllerTypeHiddenNavBar) {
            _swipeTableView.swipeHeaderTopInset = 0;
        }
    }
    return _swipeTableView;
}

- (UIView *)tableViewHeader {
    if (nil == _tableViewHeader) {
        UIImage * headerImage = [UIImage imageNamed:@"onepiece_kiudai"];
        self.tableViewHeader = [[STHeaderView alloc]init];
        _tableViewHeader.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height * (headerImage.size.height/headerImage.size.width));
        _tableViewHeader.backgroundColor = [UIColor whiteColor];
        _tableViewHeader.layer.masksToBounds = YES;
        // image view
        self.headerImageView = [[UIImageView alloc]initWithImage:nil];
        _headerImageView.contentMode = UIViewContentModeScaleAspectFill;
        _headerImageView.userInteractionEnabled = YES;
        _headerImageView.frame = _tableViewHeader.bounds;
        _headerImageView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
        [aRquestModel initializePicByName:@"星空" WithBlock:^(id obj) {
            if (!obj) return;
            NSInteger num = arc4random() % [(NSArray*)obj count];
            [self.headerImageView sd_setImageWithURL:aRUrl(obj[num]) placeholderImage:nil options:0];
        }];
        _tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapHeader:)];
        [_tableViewHeader addSubview:_headerImageView];
        [_headerImageView addGestureRecognizer:_tap];
    }
    return _tableViewHeader;
}

- (HMSegmentedControl*)hsBar{
    if (!_hsBar) {
        _hsBar = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"网易云",@"QQ",@"酷狗",@"虾米",@"伴奏"]];
        _hsBar.frame = CGRectMake(0, 0, aR_WIDTH, 40);
        _hsBar.selectedSegmentIndex = 0;
        MJWeakSelf
        [_hsBar setIndexChangeBlock:^(NSUInteger index) {
            [weakSelf.swipeTableView scrollToItemAtIndex:index animated:NO];
            weakSelf.index = index;
        }];
    }
    return _hsBar;
}

- (UIImageView*)gifView{
    if (!_gifView) {
        NSMutableArray *armutArr = @[].mutableCopy;
        for (NSInteger i = 0; i < 6; i++) {
            [armutArr addObject:[UIImage imageNamed:[NSString stringWithFormat:@"cm2_topbar_icn_playing%ld",(long)i]]];
        }
        _gifView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
        _gifView.image = [aR_Image(@"cm2_topbar_icn_playing0") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        _gifView.animationImages = armutArr;
        _gifView.animationDuration = .5f;
        _gifView.animationRepeatCount = 1000000;
    }
    return _gifView;
}

#pragma mark ---------- ViewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    BOOL disableBarScroll = _type == STControllerTypeDisableBarScroll;
    _dataDic = [@{} mutableCopy];
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName : [UIFont boldSystemFontOfSize:16]};
    self.title = self.songName;
    [self.view addSubview:self.swipeTableView];
    
    self.rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightBtn.frame = CGRectMake(0, 0, 25, 25);
    [_rightBtn addTarget:self action:@selector(setSwipeTableHeader:) forControlEvents:UIControlEventTouchUpInside];
    _rightBtn.userInteractionEnabled = YES;
    [_rightBtn addSubview:self.gifView];
    UIBarButtonItem * rightBarItem = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn];
    self.leftBarItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(setSwipeTableBar:)];
    _leftBarItem.tintColor = [UIColor whiteColor];
    self.navigationItem.leftBarButtonItem = disableBarScroll?nil:_leftBarItem;
    self.navigationItem.rightBarButtonItem = disableBarScroll?nil:rightBarItem;
    
    // 根据滚动后的下标请求数据
//    [self getDataAtIndex:0];
    
    [self bingModel];
}

#pragma mark --------- Data Reuqest
-(void)saveAndSendData:(id)numberObject index:(NSInteger)index{
    ((void (*)(void *, SEL, NSArray*, NSInteger))objc_msgSend)((__bridge void *)(self.swipeTableView.currentItemView),@selector(refreshWithData:atIndex:), numberObject,index);
    [_dataDic setObject:numberObject forKey:@(index)];
}


#pragma mark --------------- SwipeTableView M
- (NSInteger)numberOfItemsInSwipeTableView:(SwipeTableView *)swipeView {
    return 5;
}

- (UIScrollView *)swipeTableView:(SwipeTableView *)swipeView viewForItemAtIndex:(NSInteger)index reusingView:(UIScrollView *)view {
    switch (_type) {
        case STControllerTypeNormal:{
            CustomTableView * tableView = (CustomTableView *)view;
            if (nil == tableView) {
                tableView = [[CustomTableView alloc]initWithFrame:swipeView.bounds style:UITableViewStylePlain];
                tableView.backgroundColor = aR_BGColor;
            }
            id data = _dataDic[@(index)];
            [tableView refreshWithData:data atIndex:index];
            MJWeakSelf
            [tableView setCellBack:^(MusicModel *model) {
                if(!model) return;
                [[aRquestModel new] downFileFromServer:model.fileName CallbackPath:^(NSURL *aRPath, NSError *error,CGFloat count) {
                    [MusicTool sharedMusicTool].playingIndex = index;
                    [[MusicTool sharedMusicTool] prepareToPlayWithMusic:aRPath];
                    PlayViewController *p = [PlayViewController new];
                    p.music = model;
                    [weakSelf.navigationController pushViewController:p animated:YES];
                }];
            }];
            view = tableView;
        }
            break;
        default:
            break;
    }
    return view;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:_type == STControllerTypeHiddenNavBar animated:animated];
    [MusicTool sharedMusicTool].isPlaying?[self.gifView startAnimating] : [self.gifView stopAnimating];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

#pragma mark-------BingModel
-(void)bingModel {
    self.stModel = [STViewModel new];
    @weakify(self);
//    [self.stModel.dCommand.executing subscribeNext:^(id x) {
//       //是否在运行
//    }];
//    [self.stModel.dCommand.executionSignals.flatten subscribeNext:^(id x) {
//        NSLog(@"result:%@",x);
//    }];
    
    [RACObserve(self, index) subscribeNext:^(id x) {
        @strongify(self)
        self.stModel.index = _index;
        self.stModel.songName = _songName;
        if (nil != _dataDic[@(_index)]) return;
        [[self.stModel.dCommand execute:@1] subscribeNext:^(id x) {
            [self saveAndSendData:x index:self.index];
        }];
    }];
    
    //图片
    [[self rac_signalForSelector:@selector(tapHeader:)] subscribeNext:^(id x) {
        STImageController * imageVC = [[STImageController alloc]init];
        imageVC.transitioningDelegate = self;
        [self presentViewController:imageVC animated:YES completion:nil];
    }];
    //播放点击事件
    [[self rac_signalForSelector:@selector(setSwipeTableHeader:)] subscribeNext:^(id x) {
        if ([MusicTool sharedMusicTool].playingIndex != -1){
            MusicModel *music = [MusicTool sharedMusicTool].musicList[[MusicTool sharedMusicTool].playingIndex];
            PlayViewController *playerVc = [[PlayViewController alloc]init];
            playerVc.music = music;
            [self.navigationController pushViewController:playerVc animated:YES];
        } else {
            MusicModel *music = [MusicTool sharedMusicTool].musicList[0];
            PlayViewController *playerVc = [[PlayViewController alloc]init];
            playerVc.music = music;
            MJWeakSelf
            [[aRquestModel new] downFileFromServer:music.fileName CallbackPath:^(NSURL *aRPath, NSError *error,CGFloat count) {
                [MusicTool sharedMusicTool].playingIndex = 0;
                [[MusicTool sharedMusicTool] prepareToPlayWithMusic:aRPath];
                PlayViewController *p = [PlayViewController new];
                p.music = music;
                [weakSelf.navigationController pushViewController:p animated:YES];
            }];
        }
    }];
    //返回
    [[self rac_signalForSelector:@selector(setSwipeTableBar:)] subscribeNext:^(id x) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    /*
     SwipeTableViewDataSourceProtocol
     */
    [[self rac_signalForSelector:@selector(swipeTableViewCurrentItemIndexDidChange:) fromProtocol:@protocol(SwipeTableViewDelegate)] subscribeNext:^(id x) {
        [_hsBar setSelectedSegmentIndex:((SwipeTableView*)[(RACTuple*)x first]).currentItemIndex animated:YES];
    }];
    
    [[self rac_signalForSelector:@selector(swipeTableViewDidEndDecelerating:) fromProtocol:@protocol(SwipeTableViewDelegate)] subscribeNext:^(id x) {
        @strongify(self)
        self.index = ((SwipeTableView*)[(RACTuple*)x first]).currentItemIndex;
    }];
}


@end
